<template>
    <fieldset>
        <legend>失效函数的应用</legend>
        <h1 id="content">
            {{content}}
        </h1>

        <button v-for="(btn,index) in buttons" :key="index" :class="{active:index+1===page}" @click="pageChange(index+1)">第{{index+1}}页</button>
        
    </fieldset>
</template>
<script setup>
    import {ref,onMounted, reactive,watchEffect} from "vue"
    import CancelPromise from "./cancelPromise"
     
    // 声明三个按钮
    let buttons = reactive(['第1页','第2页','第3页'])

    //模拟的三个请求
    let api1 = (signal) => new CancelPromise((resolve, reject) => {
        setTimeout(() => {
            resolve('第一页的数据')
        }, 1000)
    },signal)

    let api2 = (signal) => new CancelPromise ((resolve, reject) => {
        setTimeout(() => {
            resolve('第二页的数据')
        }, 1500)
    },signal)

    let api3 = (signal) => new CancelPromise ((resolve, reject) => {
        setTimeout(() => {
            resolve('第三页的数据')
        }, 2000)
    },signal)

    //模拟请求
    let api = {
        api1,
        api2,
        api3
        
    }

    //声明一个响应式变量
    let content = ref('')
    //声明一个三分的响应式变量作为按钮激活条件
    let page = ref(1)
    //点击分页获取分页数据Z
    let pageChange = (pageSize)=>{
        // fetchData(pageSize)
        page.value = pageSize//给三方作为激活条件的变量进行赋值
    }

    //封装一个获取内容的方法
    /**
     * 
     * @param {Number} pageSize 传递给后台的页码
     * @param {Object} signal 控制器(AbortControll)的signal对象
     */
    let fetchData = (pageSize = 1, signal) => (
        api['api' + pageSize](signal)
        .then(res => {
            console.log(res)
            content.value = res;    
        })
    )

    //使用watchEffect
    watchEffect(invalidate => {
        //声明一个控制
        let abortController = new AbortController();
        let signal = abortController.signal;
        fetchData(page.value, signal)
        invalidate(() => {
            abortController.abort()//页面切换之前,取消上一个promise
        })
    })
    //页面加载的时候获取第一页数据
    // onMounted(()=>{
    //     fetchData()
    // })
</script>
<style scoped>
    .active{
        background-color: palegreen;
    }
</style>